package com.dp.service.impl3;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.pojo.NewsVo;
import com.dp.util.DataMap;
import com.dp.vo.NewsGroup;
import com.dp.vo.NewsSystemPopumsg;

@Service
@Transactional
public class SystemPopumsgServiceImpl3 extends BaseImpl {
	/**
	 * 得到系统消息记录数
	 * 
	 * @return
	 */
	public Long findSystemPopumsgCount(DataMap dataMap) {
		String userids=(String)dataMap.get("userids");
		String hql = "SELECT count(s) FROM NewsSystemPopumsg s where 1=1 and msgcontenttype is null";
		if(userids!=null){
			hql+=" AND msgcreater in ("+userids+")";
		}
		Object obj = getSingleResult(hql);
		if (obj == null) {
			return Long.valueOf(0 + "");
		} else {
			return (Long) obj;
		}
	}

	/**
	 * 得到系统消息记录,分页
	 * 
	 * @return
	 */
	public List<NewsSystemPopumsg> findAllSystemPopumsg(DataMap dataMap,int firstrow, int maxrow) {
		JsonPage jpage=(JsonPage)dataMap.get("jpage");
		String userids=(String)dataMap.get("userids");
//		String hql = "SELECT s FROM NewsSystemPopumsg s where 1=1  order by s.msgid desc";
		String hql = "SELECT s FROM NewsSystemPopumsg s where 1=1 and msgcontenttype is null";//  order by s.msgid desc";
		if(userids!=null){
			hql+=" AND msgcreater in ("+userids+")";
		}
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
//				if("contentname".equals(jpage.getSidx())){
//					sql+=" order by nct.contenttitle";
//				}else{
//					sql+=" order by nc."+jpage.getSidx();
//					}
				hql += " order by "+jpage.getSidx();
						
				hql+=" "+jpage.getSord();
			}
		}
		logger.info("hql:"+hql);
		return getQueryList(hql, firstrow, maxrow);
	}
	
	/**
	 * 根据msgid得到对应的系统消息记录
	 * 
	 * @return
	 */
	public NewsSystemPopumsg findSystemPopumsg(int msgid) {
		
//		String hql = "SELECT s FROM NewsSystemPopumsg s where 1=1  order by s.msgid desc";
		String hql = "SELECT s FROM NewsSystemPopumsg s where msgid="+msgid;//  order by s.msgid desc";
		
		logger.info("hql:"+hql);
		NewsSystemPopumsg newsSystemPopumsg = (NewsSystemPopumsg) getSingleResult(hql);
		return newsSystemPopumsg;
	}

	
	/**
	 * 增加消息和用户组间的关系
	 * 
	 * @param msgid,groupruleids
	 * @return Boolean
	 */
	public Boolean setSystempopumsgGroup(Integer msgid, String groupruleids) {
		for (String groupruleid : groupruleids.split(",")) {
			String sql = "insert into news_systempopumsggroup (msgid,groupruleid) values ("
					+ msgid
					+ ","
					+ groupruleid + ")";
			try {
				logger.info("sql:"+sql);
				int iCode = updateNativeQuery(sql);
				if (iCode < 0) {
					return false;
				}
			} catch (Exception e) {
				log.info("setSystempopumsgGroup fail !!!" + e.getMessage());
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/*public String getGroupBymsgid(Integer msgid) {
		String grouprulenames = "";
		String sql = "select grou.grouprulename from news_group grou "
				+ " join news_systempopumsggroup msggroup on msggroup.groupruleid= grou.groupruleid"
				+ " join news_systempopumsg msg on msg.msgid=msggroup.msgid"
				+ " where msg.msgid=" + msgid;
		List grouprulenamesList = getNativeQuery(sql);
		if (grouprulenamesList.size() > 0) {
			for (int i = 0; i < grouprulenamesList.size(); i++) {
				if (i == 0) {
					grouprulenames = (String) grouprulenamesList.get(i);
				} else {
					grouprulenames += "," + (String) grouprulenamesList.get(i);
				}
			}
		}
		return grouprulenames;
	}*/

	/**
	 * 更新消息和用户组间的关系
	 * 
	 * @param msgid,grouprulenames
	 * @return Boolean
	 */
	/*public Boolean updateSystempopumsgGroup(Integer msgid, String grouprulenames) {
		String sql = "delete from news_systempopumsggroup where msgid=" + msgid
				+ "";
		int iCode = updateNativeQuery(sql);
		if (iCode < 0) {
			return false;
		}
		if (!"".equals(grouprulenames)) {

			for (String grouprulename : grouprulenames.split(",")) {
				sql = "insert into news_systempopumsggroup (msgid,groupruleid) values ("
						+ msgid
						+ ",(select groupruleid from news_group where grouprulename='"
						+ grouprulename + "'))";
				try {
					iCode = updateNativeQuery(sql);
					if (iCode < 0) {
						return false;
					}
				} catch (Exception e) {
					log.info("updateSystempopumsgGroup fail !!!"
							+ e.getMessage());
					e.printStackTrace();
					return false;
				}

			}
		}
		return true;
	}*/
	
	
	
	/**
	 * 更新消息和用户组间的关系
	 * 
	 * @param msgid,groupruleids
	 * @return Boolean
	 */
	public Boolean updateSystempopumsgGroup2(Integer msgid, String groupruleids) {
		String sql = "delete from news_systempopumsggroup where msgid=" + msgid
				+ "";
		int iCode = updateNativeQuery(sql);
		if (iCode < 0) {
			return false;
		}
		if (!"".equals(groupruleids)) {

			for (String groupruleid : groupruleids.split(",")) {
				sql = "insert into news_systempopumsggroup (msgid,groupruleid) values ("
						+ msgid
						+ ","
						+ groupruleid + ")";
				try {
					iCode = updateNativeQuery(sql);
					if (iCode < 0) {
						return false;
					}
				} catch (Exception e) {
					log.info("updateSystempopumsgGroup fail !!!"
							+ e.getMessage());
					e.printStackTrace();
					return false;
				}

			}
		}
		return true;
	}

	/**
	 * 删除系统消息
	 * 
	 * @return
	 */
	public Boolean deleteNewsSystemPopumsg(String ids) {
		Boolean resultb=true;
		try {
			if(ids!=null&&!"".equals(ids)){
				String [] idarys=ids.split(",");
				for(String id:idarys){
					this.sql="select count(*)  from news_clientgetmsg where msgid="+id;
					int i=this.getOneInt();
					if(i>0){
						this.sql="delete from news_systempopumsggroup where msgid="+id;
						this.em.createNativeQuery(sql).executeUpdate();
						
						this.sql="delete from news_systempopumsg where msgid="+id;
						this.em.createNativeQuery(sql).executeUpdate();
					}else{
						if(idarys.length==1){
							resultb=null;
						}
					}
				}
			}else{
				resultb=false;
			}
		} catch (Exception e) {
			logger.error("deleteNewsSystemPopumsg fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
		}
		return resultb;
	}

	/**
	 * 删除系统消息 图片
	 * 
	 * @param msgid
	 * @return
	 */
	public int delMsgPic(String msgid) {
		int iCode = 0;
		try {
			String sql = "update news_systempopumsg set msgpicture=null where msgid="
					+ msgid + "";
			iCode = updateNativeQuery(sql);
			if (iCode < 0) {
				return -1;
			} else {
				return 1;
			}
		} catch (Exception e) {
			log.info("delMsgPic fail !!!" + e.getMessage());
			e.printStackTrace();
			iCode = -1;
		}
		return iCode;
	}
	
	/**
	 * 根据msgid获得其对应的关联用户组
	 */
	public List getSelectedgroupidListbyid(int msgid){
		
//		String hql = "SELECT s FROM NewsSystemPopumsg s where 1=1  order by s.msgid desc";
		String hql = "SELECT groupruleid FROM news_systempopumsggroup where msgid="+msgid;//  order by s.msgid desc";
		
		logger.info("hql:"+hql);
		
		return getNativeQuery(hql);
	}

	/**
	 * 根据groupruleids这个List来获取groupList
	 */
	public List<NewsGroup> getSelectedgroupListbyids(List Selectedgroupids){
		List<NewsGroup> groupList = new ArrayList<NewsGroup>();
		int lengthOfList = Selectedgroupids.size();
		Query query;
		NewsGroup o;
		try{
			for(int i = 0;i < lengthOfList;i++){
				logger.info("Selectedgroupids.get("+i+")="+Selectedgroupids.get(i));
				
				o = this.em.find(NewsGroup.class, Selectedgroupids.get(i));
				groupList.add(o);
			}
		}catch(Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return groupList;
	}
	
	/**
	 * 增加消息和用户组间的关系
	 * 
	 * @param msgid,groupruleids
	 * @return Boolean
	 */
	public Boolean setSystempopumsgGroup2(Integer msgid, String groupruleids) {
		for (String groupruleid : groupruleids.split(",")) {
			String sql = "insert into news_systempopumsggroup (msgid,groupruleid) values ("
					+ msgid
					+ ","
					+ groupruleid + ")";
			try {
				logger.info("sql:"+sql);
				int iCode = updateNativeQuery(sql);
				if (iCode < 0) {
					return false;
				}
			} catch (Exception e) {
				log.info("setSystempopumsgGroup fail !!!" + e.getMessage());
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	public boolean invalidateE(String ids) {
		Boolean resultb=true;
		try {
			
			if(ids!=null&&!"".equals(ids)){
				String [] idarys=ids.split(",");
				SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String DateS=fmt_temp.format(new java.util.Date());
				this.sql="update news_systempopumsg set msginvalidtime=?,flag=2 where msgid=?";
	       Query	query=em.createNativeQuery(sql);
			
				for(String id:idarys){
					query.setParameter(1, DateS);
					query.setParameter(2, id);
					query.executeUpdate();
				}
				
			}else{
				resultb=false;
			}
		} catch (Exception e) {
			logger.error("invalidateE fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
		}
		return resultb;
	}
	
	//add for iphone push
	public boolean insertPushMsg(int msgid) 
	{
		NewsSystemPopumsg msg = this.findSystemPopumsg(msgid);
		sql="select clientid,token from news_iphonevalidclient";
		Query query = em.createNativeQuery(sql);
		int clientid=0;
		String token="";
		List<Object[]> lll= query.getResultList();
		if(lll.size()>0 && msg!=null)
		{
			for(int i=0;i<lll.size();i++){
				clientid=(Integer)lll.get(i)[0];
				token=(String)lll.get(i)[1];
				sql="insert into news_iphonewillsendmsg(clientid,token,msgid,msgtype,msg,msgtipe) values(?,?,?,?,?,?)";
				query=em.createNativeQuery(sql);
				query.setParameter(1,clientid);
				query.setParameter(2,token);
				query.setParameter(3,msg.getMsgid());
				query.setParameter(4,msg.getMsgaction());
				query.setParameter(5,msg.getMsgmoretext());
				query.setParameter(6,"");
				query.executeUpdate();
			}
		}
		return true;
	}
	
	/**
	 * 机构已关联用户组对象集合
	 * @param spcode
	 * @return
	 */
	/*public List<NewsGroup> getSelectedgroupListbySpcode(String spcode) {
		List<NewsGroup> groupllist=new ArrayList<NewsGroup>();
		NewsGroup group=null;
		TAreainfo area=null;
		try {
	        this.init();
			this.sql="select ng.groupruleid,ng.grouprulename,ng.mlocale,(select areaname from t_areainfo where areaid=ng.marea) areaname from news_group ng where ng.groupruleid in (select rulegroup from t_spcode_rulegroup where spcode='"+spcode+"')";
			rs2=stmt.executeQuery(sql);
			while(rs2.next()){
				group=new NewsGroup();
				group.setGroupruleid(rs2.getInt("groupruleid"));
				group.setGrouprulename(rs2.getString("grouprulename"));
				group.setMlocale(rs2.getString("mlocale"));
				area=new TAreainfo();
				area.setAreaname(rs2.getString("areaname"));
				groupllist.add(group);
			}
			conn.commit(); 
		} catch (Exception e) {
			logger.error("getSelectedgroupListbySpcode fail !!!" + e.getMessage());
			e.printStackTrace();
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
		} finally {
			this.closeAll();
		}
		return groupllist;
	}*/
}
